package com.iotimc.attendancesystem.util;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;


/**
 * Created by wj on 2016/8/2.
 *
 * @author  wj
 */
public class TtsUtil {
    private static TextToSpeech tts;

    private static TtsUtil ttsUtil;
    private final int mInt;

    public static TtsUtil init(Context context) {
        if (ttsUtil == null) {
            ttsUtil = new TtsUtil(context);
        }
        return ttsUtil;
    }

    private TtsUtil(Context con) {
        tts = new TextToSpeech(con, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int supported = tts.setLanguage(Locale.CHINA);
                    Log.d("TAG", "Updating engine: Successfully bound to the engine: " +
                            tts.getDefaultEngine());
                } else {
                    Log.d("TAG", "Updating engine: Failed to bind to engine, reverting.");
                }
            }
        });
        mInt = 2;
        if (tts.getEngines().size() >= mInt) {
            tts.setEngineByPackageName(tts.getEngines().get(1).name);
        }
    }

    /**
     * 播放tts，如果正在播放tts则停止之前的播放最新的
     *
     * @param message
     */
    public static void ttsSpeek(final String message) {
        if (tts != null) {
            tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    /**
     * 如果正在播放tts，则不播放新的tts
     *
     * @param message
     */
    public static void ttsSpeek2(String message) {
        if (tts != null && !tts.isSpeaking()) {
            tts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    public void ttsClose() {
        tts.shutdown();
    }
}
